import asyncio, os, smtplib, socket
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from contextlib import closing  # 用于自动关闭 socket

class WowHelper:
  @staticmethod
  def send_email(message):
    if not WowHelper.check_network():
      return False
    send_status = False
    smtp_server = os.getenv("EMAIL_SMTP_HOST")   # 例如: smtp.qq.com, smtp.gmail.com
    smtp_port = int(os.getenv("EMAIL_SMTP_PORT", "465"))                 # 常用端口：25/465(SSL)/587(TLS)
    username = os.getenv("EMAIL_SMTP_USER")
    password = os.getenv("EMAIL_SMTP_PASS")   # 注意：不是邮箱密码，而是 SMTP 授权码

    # 发件人和收件人
    sender = os.getenv("EMAIL_SMTP_USER")
    receiver = os.getenv("EMAIL_SMTP_RECV")

    # 构建邮件内容
    msg = MIMEMultipart()
    msg["From"] = formataddr(("WOW Bot", sender))
    msg["To"] = receiver
    msg["Subject"] = "WOW Tip"
    
    msg.attach(MIMEText(message, "plain", "utf-8"))
    server = None
    try:
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server.login(username, password)
        server.sendmail(sender, receiver, msg.as_string())
        print("邮件发送成功！")
        send_status = True
    except Exception as e:
        print("邮件发送失败：", e)
        send_status = False
    finally:
        if server:
            server.quit()
    return send_status
            
  @staticmethod
  def check_network(timeout=1):
    try:
      with closing(socket.create_connection(('114.114.114.114', 53), timeout)):
        return True
    except OSError:
      return False